#!/usr/bin/env python3
# coding:utf-8
""" 
解析请求的数据
"""
import json
import time
import subprocess
import threading
from flask import Flask, request, render_template

app = Flask(__name__)

async_cmd_run_flag = False
cmd_line = ""


def run_shell_realtime_output(cmd):
    global cmd_line
    global async_cmd_run_flag
    p = subprocess.Popen(
        cmd,
        shell=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        universal_newlines=True,
    )
    # 循环读取输出
    for line in iter(p.stdout.readline, ""):
        cmd_line += line.strip() + "\n"

    return_code = p.wait()
    if return_code != 0:
        print(f"return code: {return_code}")
    async_cmd_run_flag = False


def async_run_cmd(cmd):
    global async_cmd_run_flag
    async_cmd_run_flag = True

    task = threading.Thread(target=run_shell_realtime_output, args=(cmd,), daemon=True)
    task.start()


@app.route("/ping_start", methods=["GET", "POST"])
def ping_start():
    global shell_cmd_run_flag
    global cmd_line
    data = request.json
    print(data)
    cmd = f"ping {data['ip']} -c {data['count']} -w {data['timeout']}"

    resp = {"status": "run", "msg": ""}
    if async_cmd_run_flag:
        resp["msg"] = cmd_line
        cmd_line = ""
    elif async_cmd_run_flag == False and data["cmd_start"] == True:
        async_run_cmd(cmd)
        resp["msg"] = cmd
    else:
        resp["status"] = "finish"
        resp["msg"] = cmd_line
        cmd_line = ""

    return resp


@app.route("/ping_test", methods=["GET"])
def ping_test():
    return render_template("ping.html")


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8800)
